package com.qingyun.web.controller.tiktok;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.domain.model.TiktokUser;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.quartz.domain.TiktokPushTask;
import com.qingyun.quartz.mapper.TiktokPushTaskMapper;
import com.qingyun.quartz.service.ITiktokPushTaskService;
import com.qingyun.quartz.task.VideoSendService;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokCoupon;
import com.qingyun.shop.domain.TiktokCouponDraw;
import com.qingyun.shop.domain.TiktokShop;
import com.qingyun.shop.domain.TiktokShopStaffPush;
import com.qingyun.shop.domain.vo.*;
import com.qingyun.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname TikTokCouponController
 * @Author dyh
 * @Date 2021/9/14 17:43
 */
@Api(tags = "抖音h5 优惠卷")
@RequestMapping("/tikTok/Coupon/api")
@RestController
@Slf4j
public class TikTokCouponController {

	@Autowired
	private ITiktokCouponService iTiktokCouponService;

	@Autowired
	private ITiktokActivityService iTiktokActivityService;

	@Autowired
	private ITiktokShopService shopService;

	@Autowired
	private ITiktokCouponDrawService couponDrawService;

	@Resource
	private TiktokPushTaskMapper pushTaskMapper;

	@Autowired
	private VideoSendService videoSendService;

	@Autowired
	private ITiktokShopStaffPushService shopStaffPushService;

	@Autowired
	private MapperFacade mapperFacade;

	@Autowired
	private RedisCache redisCache;

	@Cacheable(cacheNames = "selectCoupon", key = "#activityId")
	@ApiOperation("获取活动优惠卷列表")
	@GetMapping("/getCoupons")
	public AjaxResult selectCoupon(Long activityId, Integer status){
		List<TiktokCouponVo> tiktokCouponVos = iTiktokCouponService.selectCouponVoByActivityId(activityId, status);
		return AjaxResult.success(tiktokCouponVos);
	}

	/**
	 * type 0直接发送 1领取优惠卷发送
	 * @param activityId
	 * @param couponId
	 * @return
	 */
	@ApiOperation("用户发布视频领卷")
	@RepeatSubmit
	@PostMapping("/getCouponVideo")
	@Caching(evict={
	 @CacheEvict(cacheNames = "selectCoupon",key = "#activityId")
	})
	public AjaxResult getCoupon(Long activityId, Long couponId, @RequestParam(required = false) Long shopUserId){
		TiktokActivityVo tiktokActivityVo = iTiktokActivityService.getVoById(activityId);
		if (ObjectUtil.isNull(tiktokActivityVo)) {
			return AjaxResult.error("活动不存在");
		}
		if (!tiktokActivityVo.getStatus().equals(Constants.ONLINE)) {
           return AjaxResult.error("活动还没发布哦");
		}
		if (tiktokActivityVo.getEndDate().before(new Date())) {
			return AjaxResult.error("活动已经过期");
		}

		//领取优惠卷
		TiktokCoupon tiktokCoupon=null;
		String actityType = tiktokActivityVo.getActityType();
		if (Constants.SEND_TYPE_COUPON.equals(actityType)) {
			tiktokCoupon = iTiktokCouponService.getById(couponId);
			if (ObjectUtil.isNull(tiktokCoupon)||tiktokCoupon.getQuantity()<=0) {
				return AjaxResult.error("优惠卷已经被抢光啦，请联系商家");
			}
		}

		TiktokUser tikTokUser = SecurityUtils.getTikTokLoginUser().getTikTokUser();
		if (!tiktokActivityVo.getJoinCount().equals(Constants.JOINCOUNTSTATUS)) {
			if (couponDrawService.count(Wrappers.lambdaQuery(TiktokCouponDraw.class)
				.eq(TiktokCouponDraw::getActivityId,activityId)
				.eq(TiktokCouponDraw::getUserId,tikTokUser.getId()))>=tiktokActivityVo.getJoinCount()) {
				return AjaxResult.error("每人只能参与" + tiktokActivityVo.getJoinCount() + "次,谢谢您的参与。");
			}
		}

		//领取优惠卷
		if (Constants.SEND_TYPE_COUPON.equals(actityType)) {
			if (tiktokCoupon.getCollectionTimes().equals(1)) {
				int count = couponDrawService.count(Wrappers.lambdaQuery(TiktokCouponDraw.class)
					.eq(TiktokCouponDraw::getCouponId, tiktokCoupon.getId())
					.eq(TiktokCouponDraw::getUserId, tikTokUser.getId()));
				if (count >= tiktokCoupon.getCollectionTimes()) {
					return AjaxResult.error("你已经领取过" + count + "张啦，不能再领取了。");
				}
			}
		}

		TiktokShop tiktokShop = shopService.getById(tiktokActivityVo.getShopId());
		if (tiktokShop.getVideoCount()<=0) {
			return AjaxResult.error("商家视频转发余额不足，请联系商家。");
		}

		TiktokShopStaffPush tiktokShopStaffPush=null;
		log.warn("他妈的进来了"+shopUserId);
		if (ObjectUtil.isNotNull(shopUserId)) {
		    tiktokShopStaffPush = new TiktokShopStaffPush();
			tiktokShopStaffPush.setActivityId(activityId);
			tiktokShopStaffPush.setActivityType(Integer.parseInt(tiktokActivityVo.getActityType()));
			tiktokShopStaffPush.setShopId(tiktokShop.getId());
			tiktokShopStaffPush.setShopUserId(shopUserId);
			tiktokShopStaffPush.setCreateTime(new Date());
			tiktokShopStaffPush.setTiktokUserId(tikTokUser.getId());
		}

		tiktokShop.setVideoCount(tiktokShop.getVideoCount()-1);
		if (shopService.updateById(tiktokShop)) {
			//立即发
			if (tiktokActivityVo.getLaterSend().equals(0L)) {
				try {
					videoSendService.asyncMergeVideoSend(activityId, tikTokUser.getId(), null);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			} else {
				//延迟发送 later_send
				TiktokPushTask tiktokPushTask = new TiktokPushTask();
				tiktokPushTask.setActivityId(activityId);
				tiktokPushTask.setUserId(tikTokUser.getId());
				//多少小时后发送
				DateTime dateTime = DateUtil.offsetHour(new Date(), tiktokActivityVo.getLaterSend().intValue());
				tiktokPushTask.setSendTime(dateTime.toJdkDate());
				pushTaskMapper.insert(tiktokPushTask);
			}

            //领取优惠卷
			if (Constants.SEND_TYPE_COUPON.equals(actityType)) {
				TiktokCouponDraw tiktokCouponDraw = new TiktokCouponDraw();
				tiktokCouponDraw.setActivityId(activityId);
				tiktokCouponDraw.setCouponId(couponId);
				tiktokCouponDraw.setCouponCode(RandomUtil.randomNumbers(10));
				tiktokCouponDraw.setCreateTime(new Date());
				tiktokCouponDraw.setGetType(0);
				tiktokCouponDraw.setUseStatus(0);
				tiktokCouponDraw.setUserId(tikTokUser.getId());

				if (tiktokCoupon.getTimeType().equals(0)) {
					tiktokCouponDraw.setBeginDate(new Date());
					tiktokCouponDraw.setEndDate(DateUtil.offsetDay(new Date(), tiktokCoupon.getDays()));
				} else {
					tiktokCouponDraw.setBeginDate(tiktokCoupon.getStartTime());
					tiktokCouponDraw.setEndDate(tiktokCoupon.getEndTime());
				}
				boolean save = couponDrawService.save(tiktokCouponDraw);
				if (ObjectUtil.isNotNull(tiktokShopStaffPush)) {
					tiktokShopStaffPush.setCouponDrawId(tiktokCouponDraw.getId());
					shopStaffPushService.save(tiktokShopStaffPush);
				}
				//减扣优惠卷
				if (save) {
					tiktokCoupon.setQuantity(tiktokCoupon.getQuantity() - 1);
					iTiktokCouponService.updateById(tiktokCoupon);
					return AjaxResult.success("领取成功");
				}

			}else{
				return AjaxResult.success("发送成功");
			}
		}
		return AjaxResult.success("领取失败，请联系系统管理员");
	}

	@ApiOperation("领取优惠卷列表")
	@GetMapping("/couponInfoList")
	public AjaxResult getCouponList(Long activityId){
		List<TiktokCouponDraw> tiktokCouponDraws = iTiktokCouponService.selectCouponDownList(activityId);
		return AjaxResult.success(tiktokCouponDraws);
	}


	@ApiOperation("领取优惠卷列表 根据活动和状态查询优惠券列表 0 待使用 1已使用 2已过期")
	@GetMapping("/couponInfoListByStatus")
	public TableDataInfo<TiktokUserCouponDrawList> getCouponListByStatus(@RequestParam("activityId") Long activityId,
																		 @RequestParam("status") Integer status,
																		 @RequestParam("pageNum") Integer pageNum,
																		 @RequestParam("pageSize")Integer pageSize) {
		return iTiktokCouponService.selectCouponDownList(activityId,status);
	}

	@ApiOperation("查看优惠卷详情")
	@GetMapping("/seeCouponInfo")
	public AjaxResult selectCouponInfo(Long couponDrawId){
		TiktokCouponDrawVo couponDrawVo = couponDrawService.getVoById(couponDrawId);
		if (!couponDrawVo.getUseStatus().equals(0)) {
			return AjaxResult.error("优惠卷已经使用或者过期");
		}
		TiktokCouponVo coupon = iTiktokCouponService.getVoById(couponDrawVo.getCouponId());
		couponDrawVo.setCoupon(coupon);
		TiktokActivityVo activityVo = iTiktokActivityService.getVoById(couponDrawVo.getActivityId());
		couponDrawVo.setActivity(activityVo);
		couponDrawVo.setShop(mapperFacade.map(shopService.getById(activityVo.getShopId()), TiktokShopH5Vo.class));
		Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data",couponDrawVo);
        resultMap.put("qrcode",couponDrawVo.getCouponCode());
        return AjaxResult.success(resultMap);
	}

	@ApiOperation("查看优惠卷是否核销")
	@GetMapping("isWriteOff")
	public AjaxResult selectCheck(String qrCode){
		if(ObjectUtil.isNull(qrCode)){
			return AjaxResult.success(false);
		}
		String use = redisCache.getCacheObject("use-couponDraw-" + qrCode);
		if (ObjectUtil.isNotNull(use)&&use.equals("success")) {
			return AjaxResult.success(true);
		}
		return AjaxResult.success(false);
	}

}
